package fa7.socialcode.dao.jpa;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import fa7.socialcode.dao.ExampleDao;
import fa7.socialcode.model.Example;

public class ExampleDaoJpa implements ExampleDao {
  private static EntityManagerFactory factory;
  static {
    factory = Persistence.createEntityManagerFactory("socialcode");
  }

  private EntityManager entityManager;

  private EntityManager getEntityManager() {
    if (entityManager == null)
      entityManager = factory.createEntityManager();
    return entityManager;

  }

  public List findExamples() {
    return getEntityManager().createQuery("from Example").getResultList();
  }

  public void removeExample(Example example) {
    getEntityManager().getTransaction().begin();

    getEntityManager().remove(example);

    getEntityManager().getTransaction().commit();
  }

  public void removeExample(Long id) {
    getEntityManager().getTransaction().begin();

    getEntityManager().remove(findExample(id));

    getEntityManager().getTransaction().commit();
  }

  public void saveExample(Example example) {
    getEntityManager().getTransaction().begin();
    if (example.getId() != null) {
      getEntityManager().merge(example);
    } else {
      getEntityManager().persist(example);
    }

    getEntityManager().getTransaction().commit();
  }

  public Example findExample(Long id) {
    return getEntityManager().find(Example.class, id);
  }

}
